/**
 * 性能监控工具
 * 用于监控和优化应用性能
 */

class PerformanceMonitor {
  constructor() {
    this.metrics = {
      apiRequests: [],
      slowRequests: [],
      renderTimes: [],
      cacheHits: 0,
      cacheMisses: 0
    }
    this.maxRecords = 100 // 最大记录数
  }

  /**
   * 记录API请求
   * @param {string} url - 请求URL
   * @param {number} duration - 请求耗时（毫秒）
   * @param {boolean} cached - 是否使用缓存
   */
  recordApiRequest(url, duration, cached = false) {
    const record = {
      url,
      duration,
      cached,
      timestamp: Date.now()
    }

    this.metrics.apiRequests.push(record)
    if (cached) {
      this.metrics.cacheHits++
    } else {
      this.metrics.cacheMisses++
    }

    // 记录慢请求（超过1秒）
    if (duration > 1000) {
      this.metrics.slowRequests.push(record)
    }

    // 限制记录数量
    if (this.metrics.apiRequests.length > this.maxRecords) {
      this.metrics.apiRequests.shift()
    }
    if (this.metrics.slowRequests.length > this.maxRecords) {
      this.metrics.slowRequests.shift()
    }
  }

  /**
   * 记录渲染时间
   * @param {string} component - 组件名称
   * @param {number} duration - 渲染耗时（毫秒）
   */
  recordRenderTime(component, duration) {
    this.metrics.renderTimes.push({
      component,
      duration,
      timestamp: Date.now()
    })

    if (this.metrics.renderTimes.length > this.maxRecords) {
      this.metrics.renderTimes.shift()
    }
  }

  /**
   * 获取性能统计
   * @returns {object} 性能统计信息
   */
  getStats() {
    const apiRequests = this.metrics.apiRequests
    const renderTimes = this.metrics.renderTimes

    const avgApiDuration = apiRequests.length > 0
      ? apiRequests.reduce((sum, r) => sum + r.duration, 0) / apiRequests.length
      : 0

    const avgRenderTime = renderTimes.length > 0
      ? renderTimes.reduce((sum, r) => sum + r.duration, 0) / renderTimes.length
      : 0

    const cacheHitRate = (this.metrics.cacheHits + this.metrics.cacheMisses) > 0
      ? (this.metrics.cacheHits / (this.metrics.cacheHits + this.metrics.cacheMisses)) * 100
      : 0

    return {
      totalApiRequests: apiRequests.length,
      avgApiDuration: Math.round(avgApiDuration),
      slowRequestsCount: this.metrics.slowRequests.length,
      totalRenderTimes: renderTimes.length,
      avgRenderTime: Math.round(avgRenderTime),
      cacheHitRate: Math.round(cacheHitRate * 100) / 100,
      cacheHits: this.metrics.cacheHits,
      cacheMisses: this.metrics.cacheMisses
    }
  }

  /**
   * 获取慢请求列表
   * @param {number} limit - 返回数量限制
   * @returns {Array} 慢请求列表
   */
  getSlowRequests(limit = 10) {
    return this.metrics.slowRequests
      .sort((a, b) => b.duration - a.duration)
      .slice(0, limit)
  }

  /**
   * 清除所有记录
   */
  clear() {
    this.metrics = {
      apiRequests: [],
      slowRequests: [],
      renderTimes: [],
      cacheHits: 0,
      cacheMisses: 0
    }
  }

  /**
   * 获取性能报告
   * @returns {string} 性能报告文本
   */
  getReport() {
    const stats = this.getStats()
    const slowRequests = this.getSlowRequests(5)

    let report = '=== 性能监控报告 ===\n\n'
    report += `API请求统计:\n`
    report += `  总请求数: ${stats.totalApiRequests}\n`
    report += `  平均耗时: ${stats.avgApiDuration}ms\n`
    report += `  慢请求数: ${stats.slowRequestsCount}\n`
    report += `  缓存命中率: ${stats.cacheHitRate}%\n`
    report += `  缓存命中: ${stats.cacheHits}\n`
    report += `  缓存未命中: ${stats.cacheMisses}\n\n`

    if (slowRequests.length > 0) {
      report += `最慢的请求:\n`
      slowRequests.forEach((req, index) => {
        report += `  ${index + 1}. ${req.url} - ${req.duration}ms ${req.cached ? '(缓存)' : ''}\n`
      })
      report += '\n'
    }

    report += `渲染性能:\n`
    report += `  总渲染次数: ${stats.totalRenderTimes}\n`
    report += `  平均渲染时间: ${stats.avgRenderTime}ms\n`

    return report
  }
}

// 创建全局性能监控实例
const performanceMonitor = new PerformanceMonitor()

// 在开发环境下，定期输出性能报告
if (process.env.NODE_ENV === 'development') {
  setInterval(() => {
    const stats = performanceMonitor.getStats()
    if (stats.totalApiRequests > 0) {
      console.log('性能监控:', stats)
    }
  }, 60000) // 每分钟输出一次
}

export default performanceMonitor

